package com.ruoyi.scheduler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.ruoyi.domain.Asset;
import com.ruoyi.domain.MaterielThree;
import com.ruoyi.mapper.AssetMapper;
import com.ruoyi.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AssetSchedulerService {

    @Autowired
    AssetMapper assetMapper;
    //erp接口中获取资产信息

    @Value("${scheduler.enabled:true}")
    private boolean schedulerEnabled;
    public String getAsset() {
        String url = "http://192.168.3.35:9990/CROSS/RESTful"; // 第三方API的URL

        // 请求头信息
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("digi-key", "ACE2B8251074794AC21F8791D2BD2CC8");
        headers.put("digi-host", "{\"ver\":\"5.7\",\"prod\":\"YCRM\",\"timezone\":\"+8\",\"ip\":\"192.168.3.35\",\"id\":\"\",\"lang\":\"zh_CN\",\"acct\":\"dcms\",\"timestamp\":\"2018071990007275\"}");
        headers.put("digi-service", "{\"prod\":\"E10\",\"ip\":\"192.168.3.35\",\"name\":\"e10.oapi.asset.list.data.query.get\",\"id\":\"DemoCompany_External\"}");
        headers.put("digi-data-exchange-protocol", "1.0");
        headers.put("digi-type", "sync");

        //请求体信息
        String requestBody = "\t{\n" +
                "\t  \"std_data\": {\n" +
                "\t    \"parameter\": {\n" +
                "\t      \"page_size\": 2000,\n" +
                "\t      \"page_no\": 1,\n" +
                "\t      \"is_get_schema\": false,\n" +
                "\t      \"is_get_count\": false,\n" +
                "\t      \"conditions\": [],\n" +
                "\t      \"orders\": []\n" +
                "\t    }\n" +
                "\t  }\n" +
                "\t}\n";
        String response = null;
        try {
            // 调用Get请求
            //String response = HttpUtils.sendGet(url, headers);


            // 调用Post请求
            response = HttpUtils.sendPost(url, headers, requestBody);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    //处理erp接口数据
    public List<Asset> listAsset() throws JsonProcessingException {

        String jsonOne = StringUtils.substringAfter(getAsset(), "[");
        String jsonTwo = StringUtils.substringBefore(jsonOne, "]");
        String jsonStr = "["+jsonTwo+"]";
        ObjectMapper mapper = new ObjectMapper();

        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        List<Asset> assets = mapper.readValue(jsonStr, new TypeReference<List<Asset>>() {});

        for (Asset asset:assets){
            if (asset.getGetDate() != null && !asset.getGetDate().isEmpty()) {
                asset.setGetDate(asset.getGetDate().substring(0,10));
            }
            if (asset.getBookkeepingDate() != null && !asset.getBookkeepingDate().isEmpty()) {
                asset.setBookkeepingDate(asset.getBookkeepingDate().substring(0,10));
            }
            if (asset.getStartAmortizationDate() != null && !asset.getStartAmortizationDate().isEmpty()) {
                asset.setStartAmortizationDate(asset.getStartAmortizationDate().substring(0,10));
            }
            if (asset.getHandleConversionDate() != null && !asset.getHandleConversionDate().isEmpty()) {
                asset.setHandleConversionDate(asset.getHandleConversionDate().substring(0,10));
            }
            if (asset.getSourceDate() != null && !asset.getSourceDate().isEmpty()) {
                asset.setSourceDate(asset.getSourceDate().substring(0,10));
            }
            if (asset.getApproveDate() != null && !asset.getApproveDate().isEmpty()) {
                asset.setApproveDate(asset.getApproveDate().substring(0,10));
            }
            if (asset.getCreateDate() != null && !asset.getCreateDate().isEmpty()) {
                asset.setCreateDate(asset.getCreateDate().substring(0,10));
            }
            if (asset.getLastModifyDate() != null && !asset.getLastModifyDate().isEmpty()) {
                asset.setLastModifyDate(asset.getLastModifyDate().substring(0,10));
            }
            if (asset.getModifyDate() != null && !asset.getModifyDate().isEmpty()) {
                asset.setModifyDate(asset.getModifyDate().substring(0,10));
            }
        }
        return assets;
    }

    //定时从erp更新到数据库
    //@Scheduled(fixedRate = 60000) // 每分钟执行一次
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    //@Scheduled(fixedRate = 86400000) // 每天执行一次
    @Transactional
    public void scheduleTask(){
        // 判断是否启用定时任务
        if (!schedulerEnabled || java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("jdwp")) {
            return;
        }
        try {
            List<Asset> assetList1= assetMapper.selectAllAsset();//数据库中查所有
            List<Asset> assetList2 = listAsset();//接口中拿到的数据
            List<Asset> list =  uniqueList(assetList2,assetList1);//接口中除去数据库中重复的数据
            for(Asset asset:list){
                if(asset.getAssetNo() != null && !asset.getAssetNo().isEmpty()){
                    asset.setHistory("Y");
                    assetMapper.insertAsset(asset);
                }
            }
        } catch (JsonProcessingException e) {
            // 记录日志或处理异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他可能的异常
            e.printStackTrace();
        }
    }

    //存在主键对象的去重
    private List<Asset> uniqueList(List<Asset> source,List<Asset> target){
        if(CollectionUtils.isEmpty(source)){
            return List.of();
        }
        if(CollectionUtils.isEmpty(target)){
            return source;
        }
        return source.stream()
                .filter(sc-> target.stream().noneMatch(ta-> sc.getAssetNo()!=null&&sc.getAssetNo().equals(ta.getAssetNo())))
                .collect(Collectors.toList());
    }


}

